package org.linlinjava.litemall.brand.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.annotations.Param;
import org.linlinjava.litemall.brand.annotation.LoginUser;
import org.linlinjava.litemall.core.storage.StorageService;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/brand/storage")
@Validated
public class BrandStorageController {
    private final Log logger = LogFactory.getLog(BrandStorageController.class);

    @Autowired
    private StorageService storageService;
    @Autowired
    private LitemallOrderReportService reportService;
    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private LitemallDisputeService disputeService;
    @Autowired
    private LitemallServiceService serviceService;
    @Autowired
    private LitemallBrandAppendService brandAppendService;

    /**
     * 最常用的图片上传接口
     * @param file  文件.如果文件0kb 报错
     * @param userId  用户ID
     * @return
     * @throws IOException
     */
    @PostMapping("/create")
    public Object create(@RequestParam("file") MultipartFile file, @LoginUser Integer userId) throws IOException {
        String originalFilename = file.getOriginalFilename();
        LitemallStorage litemallStorage = storageService.store(file.getInputStream(), file.getSize(),
                file.getContentType(), originalFilename);
        if (litemallStorage == null) {
            return ResponseUtil.fail(403, "您上传的图片不合法，请稍后再试");
        }
        logger.info("(brand)userId: " + userId + ", uploadTime: " + new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss").format(new Date())
        + ", uploadFile: " + file.getOriginalFilename() + ", uploadSize: " + file.getSize());
        return ResponseUtil.ok(litemallStorage);
    }

    /**
     * 访问特殊储存对象 report_ 是商户检测结果的报表  bankPay_是??   license_是商户的上传证书   template_是???
     **/
    @GetMapping("/view")
    public ResponseEntity<Resource> view(@Param(value = "fileName") String fileName, HttpServletRequest request, @LoginUser Integer id) {
        String type = fileName.split("_")[0];
        Integer belong = serviceService.getBelong(id);
        if (belong == null) {
            return ResponseEntity.badRequest().build();
        }
        if ("report".equals(type)) {
            LitemallOrderReport storageInfo = reportService.findByName(fileName);
            if (storageInfo == null) {
                return ResponseEntity.notFound().build();
            }
            if ("order".equals(storageInfo.getType())) {
                LitemallOrder order = orderService.findById(storageInfo.getOrderId());
                boolean legalAdmin = belong.equals(0);
                boolean legalBrand = belong.equals(order.getBrandId());
                if (!legalAdmin && !legalBrand) {
                    ResponseEntity.badRequest().build();
                }
                String realPath = System.getProperty("user.dir");
                File file = new File(realPath + "/report/" + fileName);
                try {
                    Path path = file.toPath();
                    String mimeType = Files.probeContentType(path);
                    Resource resource = new UrlResource(path.toUri());
                    return ResponseEntity.ok().contentType(MediaType.parseMediaType(mimeType)).body(resource);
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResponseEntity.notFound().build();
                }
            }
            else if ("dispute".equals(storageInfo.getType())) {
                LitemallDisputeOrder disputeOrder = disputeService.findOrderById(storageInfo.getOrderId());
                boolean legalAdmin = belong.equals(0);
                boolean legalBrand = belong.equals(disputeOrder.getBrandId());
                if (!legalAdmin && !legalBrand) {
                    return ResponseEntity.badRequest().build();
                }
                String realPath = System.getProperty("user.dir");
                File file = new File(realPath + "/report/" + fileName);
                try {
                    Path path = file.toPath();
                     String mimeType = Files.probeContentType(path);
                    Resource resource = new UrlResource(path.toUri());
                    return ResponseEntity.ok().contentType(MediaType.parseMediaType(mimeType)).body(resource);
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResponseEntity.notFound().build();
                }
            }
        }
        else if ("bank".equals(type)) {
            LitemallOrder order = orderService.findByBankCertificate(fileName);
            LitemallDisputeOrder disOrder = disputeService.findByBankCertificate(fileName);
            if (order == null && disOrder == null) {
                return ResponseEntity.badRequest().build();
            }
            Integer orderBrand = order == null ? disOrder.getBrandId() : order.getBrandId();
            boolean legalAdmin = belong.equals(0);
            boolean legalBrand = belong.equals(orderBrand);
            if (!legalAdmin && ! legalBrand) {
                ResponseEntity.badRequest().build();
            }
            String realPath = System.getProperty("user.dir");
            File file = new File(realPath + "/bankPay/" + fileName);
            try {
                Path path = file.toPath();
                String mimeType = Files.probeContentType(path);
                Resource resource = new UrlResource(path.toUri());
                MediaType mediaType = MediaType.parseMediaType(mimeType);
                return ResponseEntity.ok().contentType(mediaType).body(resource);
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.notFound().build();
            }
        }
        else if ("license".equals(type)) {
            String realPath = System.getProperty("user.dir");
            File file = new File(realPath + "/license/" + fileName);
            try {
                Path path = file.toPath();
                String mimeType = Files.probeContentType(path);
                Resource resource = new UrlResource(path.toUri());
                return ResponseEntity.ok().contentType(MediaType.parseMediaType(mimeType)).body(resource);
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.notFound().build();
            }
        }
        else if ("template".equals(type)) {
            String realPath = System.getProperty("user.dir");
            File file = new File(realPath + "/template/" + fileName);
            try {
                Path path = file.toPath();
                String mimeType = Files.probeContentType(path);
                Resource resource = new UrlResource(path.toUri());
                return ResponseEntity.ok().contentType(MediaType.parseMediaType(mimeType)).body(resource);
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.notFound().build();
            }
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 下载特殊储存对象
     **/
    @GetMapping("/down")
    public ResponseEntity<Resource> down(@Param(value = "fileName") String fileName, HttpServletRequest request, @LoginUser Integer id) {
        String type = fileName.split("_")[0];
        Integer belong = serviceService.getBelong(id);
        if (belong == null) {
            return ResponseEntity.badRequest().build();
        }
        if ("report".equals(type)) {
            LitemallOrderReport storageInfo = reportService.findByName(fileName);
            if (storageInfo == null) {
                return ResponseEntity.notFound().build();
            }
            if ("order".equals(storageInfo.getType())) {
                LitemallOrder order = orderService.findById(storageInfo.getOrderId());
                boolean legalAdmin = belong.equals(0);
                boolean legalBrand = belong.equals(order.getBrandId());
                if (!legalAdmin && !legalBrand) {
                    ResponseEntity.badRequest().build();
                }
                String realPath = System.getProperty("user.dir");
                File file = new File(realPath + "/report/" + fileName);
                try {
                    Path path = file.toPath();
                     String mimeType = Files.probeContentType(path);
                    Resource resource = new UrlResource(path.toUri());
                    return ResponseEntity.ok().contentType(MediaType.parseMediaType(mimeType)).header(HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename=\"" + file.getName() + "\"").body(resource);
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResponseEntity.notFound().build();
                }
            }
            else if ("dispute".equals(storageInfo.getType())) {
                LitemallDisputeOrder disputeOrder = disputeService.findOrderById(storageInfo.getOrderId());
                boolean legalAdmin = belong.equals(0);
                boolean legalBrand = belong.equals(disputeOrder.getBrandId());
                if (!legalAdmin && !legalBrand) {
                    return ResponseEntity.badRequest().build();
                }
                String realPath = System.getProperty("user.dir");
                File file = new File(realPath + "/report/" + fileName);
                try {
                    Path path = file.toPath();
                     String mimeType = Files.probeContentType(path);
                    Resource resource = new UrlResource(path.toUri());
                    return ResponseEntity.ok().contentType(MediaType.parseMediaType(mimeType)).header(HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename=\"" + file.getName() + "\"").body(resource);
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResponseEntity.notFound().build();
                }
            }
        }
        else if ("bank".equals(type)) {
            LitemallOrder order = orderService.findByBankCertificate(fileName);
            LitemallDisputeOrder disOrder = disputeService.findByBankCertificate(fileName);
            if (order == null && disOrder == null) {
                return ResponseEntity.badRequest().build();
            }
            Integer orderBrand = order == null ? disOrder.getBrandId() : order.getBrandId();
            boolean legalAdmin = belong.equals(0);
            boolean legalBrand = belong.equals(orderBrand);
            if (!legalAdmin && ! legalBrand) {
                ResponseEntity.badRequest().build();
            }
            String realPath = System.getProperty("user.dir");
            File file = new File(realPath + "/bankPay/" + fileName);
            try {
                Path path = file.toPath();
                 String mimeType = Files.probeContentType(path);
                Resource resource = new UrlResource(path.toUri());
                return ResponseEntity.ok().contentType(MediaType.parseMediaType(mimeType)).header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + file.getName() + "\"").body(resource);
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.notFound().build();
            }
        }
        else if ("license".equals(type)) {
            String realPath = System.getProperty("user.dir");
            File file = new File(realPath + "/license/" + fileName);
            try {
                Path path = file.toPath();
                String mimeType = Files.probeContentType(path);
                Resource resource = new UrlResource(path.toUri());
                return ResponseEntity.ok().contentType(MediaType.parseMediaType(mimeType)).header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + file.getName() + "\"").body(resource);
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.notFound().build();
            }
        }
        else if ("template".equals(type)) {
            String realPath = System.getProperty("user.dir");
            File file = new File(realPath + "/template/" + fileName);
            try {
                Path path = file.toPath();
               // String mimeType = Files.probeContentType(path);
                String mimeType = Files.probeContentType(path);
                Resource resource = new UrlResource(path.toUri());
                return ResponseEntity.ok().contentType(MediaType.parseMediaType(mimeType)).header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + file.getName() + "\"").body(resource);
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.notFound().build();
            }
        }
        return ResponseEntity.badRequest().build();
    }

}
